<?php
/**
 * Created by PhpStorm.
 * User: zyark
 * Date: 2017/5/30
 * Time: 20:14
 */

namespace Home\Controller;


use Common\Utils\Constants;
use Common\Utils\WeChatUtils;
use Home\Logic\UserLogic;
use Think\Controller;
use Think\Log;
//您好！您正在完善个人信息，验证码：${code}。请不要把验证码泄露给其他人！30分钟内有效
//用于微风竞技用户消息通知，微风竞技官网
class WeChatMsgController extends Controller
{
//    const APPID = 'wx8ba052ae4cf7f4d9';//中线国际
//    const APPSECRET = '7db9a0d28e67a6c017efc5693be25327';


    const APPID = 'wx3bd00ee66888a243';//微风竞赛
    const APPSECRET = 'dedad9e1e43bd2b527bade0e0f0b9fc5';

//    const APPID = 'wxd1304d7d75751d77';//微风竞赛原来
//    const APPSECRET = 'c3193e1464bafba887b20abebd410a52';


    const TOKEN = 'wfjj';
    const send_text =<<<JSON
    我们是一个专注于举办线上竞技类游戏的比赛平台，在这里你能参与各种有趣的比赛以及在比赛的过程中认识来自全国各地的英雄豪杰，红颜知己！                平台秉持 “重在参与，享受比赛过程”为宗旨举办各种赛事。                                  客服微信：lzc13123087380                商务合作 ：15860104612
JSON;
    private $utils;

    public function __construct()
    {
        $this->utils = new WeChatUtils(self::APPID, self::APPSECRET, self::TOKEN);
    }

    public function getUtils()
    {
        return $this->utils;
    }

    //接收微信消息
    public function receiveMsg(){
        // 获取请求时POST：XML字符串
        // $_POST,不是key/value型因此不能使用该数组
        $xml_str = $GLOBALS['HTTP_RAW_POST_DATA'];
//        $this->firstVaild();
        // 如果没有post数据，则响应空字符串表示结束
        if (empty($xml_str)) {
            die ('');
        }
        // 解析该xml字符串，利用simpleXMLhttp://101.132.27.131/
        libxml_disable_entity_loader(true);//禁止xml实体解析，防止xml注入
        Log::write('Begin','WARN');
        $request_xml = simplexml_load_string($xml_str, 'SimpleXMLElement', LIBXML_NOCDATA);//
        Log::write('in-----');
        // 判断该消息的类型通过元素：MsgType
        switch ($request_xml->MsgType) {
            case 'event': //事件类型
                //判断具体的事件类型（关注，取消，点击）
                $event = $request_xml->Event;
                if('SCAN' == $event){
                    //扫描二维码事件
                    $this->_doQRCode($request_xml);
                    Log::write('扫描二维码事件','WARN');
                }else if('subscribe' == $event){
                    Log::write('EventKey:'.$request_xml->EventKey);
                    $array = explode('_',$request_xml->EventKey);
                    if(count($array) == 2 && !empty($array[1])){
                        $sceneId = $array[1];
                        $this->bindUser($sceneId,$request_xml->FromUserName,$request_xml->ToUserName);
                    }
                }else if('CLICK' == $event){
                    $event_key = $request_xml->EventKey.'';
                    switch ($event_key){
                        case 'customer': //客服中心
                            $media_id = 'couWdGjCWB2_HrMsiy4kTEklJ4NL85dDghDRK7slpDo';
                            $this->sendNews($media_id,$request_xml->FromUserName,$request_xml->ToUserName);
                            break;
                        case 'user_help': //用户指南
                            $media_id = 'couWdGjCWB2_HrMsiy4kTFffNtZw8PvW-lEIAfWG170';
                            $this->sendNews($media_id,$request_xml->FromUserName,$request_xml->ToUserName);
                            break;
                        case 'about_us': //关于我们
                            $this->utils->msgText($request_xml->FromUserName, $request_xml->ToUserName, '辛巴团队为您服务');
                            break;
                        case 'recharge_click':
//                            $this->utils->msgText($request_xml->FromUserName, $request_xml->ToUserName, '<a href=\'http://www.weifengyouxuan.com/index.php/Home/Recharge/new_index\'>👉点击充值钻石</a>');
                            $this->utils->msgText($request_xml->FromUserName, $request_xml->ToUserName, '点击充值链接:http://www.weifengyouxuan.com/index.php/Home/Recharge/new_index');
                            break;

//                        case 'bonus_setting':
//                            $this->utils->msgImage($request_xml->FromUserName, $request_xml->ToUserName,'8xd1Hji9Z8w99HO7_h-AkJOmZAnBidIyZuCg0G76dsc',true);
//                            break;
//                        case 'rules':
//                            $this->utils->msgImage($request_xml->FromUserName, $request_xml->ToUserName,'8xd1Hji9Z8w99HO7_h-AkGtQ0uYblFbi5fNXIIbkON0',true);
////                            $this->utils->msgText($request_xml->FromUserName, $request_xml->ToUserName, 'http://'.$_SERVER['HTTP_HOST'].'/Public/images/rules.png');
////                            $this->utils->msgImage($request_xml->FromUserName, $request_xml->ToUserName,'http://'.$_SERVER['HTTP_HOST'].'/Public/images/rules.png');
//                            break;
//                        case 'about_us':
//                            $this->utils->msgText($request_xml->FromUserName, $request_xml->ToUserName, self::send_text);
//                            break;
                    }
                }
                break;
            case 'text': // 文本消息
//                $this->_doText($request_xml);
                break;
        }
    }

    //发送图文详情
    private function sendNews($media_id,$openId,$ToUserName){
        $resource = $this->utils->getResourceByMediaId($media_id);
        $items = array();
//        $item['title'], $item['desc'], $item['picurl'], $item['url']
        foreach ($resource->news_item as $key => $value){
            $items[] = array(
                'title' => $value->title
            ,'desc' => $value->digest
            ,'picurl' => $value->thumb_url
            ,'url'   => $value->url
            );
        }
        $this->utils->msgNews($ToUserName,$openId,$items);
//        var_dump($this->utils->getResourceByMediaId('6B67JpFg8WuOniHIPVlzMRQwNPFyC5fR3bNq0LjYmzw'));
    }

    public function test(){
//        $file = fopen("./Public/images/bonus_setting.jpg", "rb");
//        $file = str_replace('\\','/',realpath(dirname(__FILE__).'/'))."/";
//        $result = $this->utils->uploadTmp(DOC_ROOT.'/Public/images/bonus_setting.jpg','image');
//        var_dump($result);
////        var_dump(getimagesize("./Public/images/bonus_setting.jpg"));
//        echo DOC_ROOT.'/Public/images/bonus_setting.jpg';
        $result = $this->utils->getFileList('image',0,10);
    }

    private function sendImage($event_key,$openId,$ToUserName){


        $image_url = 'http://'.$_SERVER['HTTP_HOST'].'/Public/images/';
        if($event_key == 'bonus_setting'){
            $image_url .='bonus_setting.jpg';
            $item['title'] = '奖金设置';
        }else if($event_key == 'rules'){
            $image_url .='rules.png';
            $item['title'] = '赛事规则';
        }
        $item['picurl'] = $image_url;
        $item['url'] = $image_url;
        $item_list[0] = $item;
        $this->utils->msgNews($ToUserName,$openId,$item_list);
    }

    /**
     * 用于第一次验证uURL合法性
     */
    public function firstVaild()
    {
        //检验签名的合法性
        if ($this->_checkSignature()) {
            //签名合法，告知微信公众平台服务器
            echo $_GET['echostr'];
            exit;
        }
    }

    /**
     * 验证签名
     * @return bool
     */
    private function _checkSignature()
    {
        $signature = $_GET["signature"];
        $timestamp = $_GET["timestamp"];
        $nonce = $_GET["nonce"];

        $token = self::TOKEN;
        $tmpArr = array($token, $timestamp, $nonce);
        sort($tmpArr, SORT_STRING);
        $tmpStr = implode($tmpArr);
        $tmpStr = sha1($tmpStr);

        if ($tmpStr == $signature) {
            return true;
        } else {
            return false;
        }
    }

    /***
     * 处理二维码事件推送
     * @param $request_xml 微信事件推送的xml对象
     */
    private function _doQRCode($request_xml){
        $sceneId = $request_xml->EventKey;//推荐人id
        $openId = $request_xml->FromUserName;//openid
        $this->bindUser($sceneId,$openId,$request_xml->ToUserName);
//        $this->utils->msgText($openId,$request_xml->ToUserName,'绑定成功,http://www.jipintc.com/');
    }

    /***
     * 处理文本回复
     * @param $request_xml 微信文本回复的xml对象
     */
    private function _doText($request_xml)
    {
        $key = $request_xml->Content . '';
        $map['keyword'] = array('like','%'.$key.'%');
        $keyword = M('wx_keyword')->where($map)->find();
        if ($keyword && !empty($keyword['reply'])) {
            $this->utils->msgText($request_xml->FromUserName, $request_xml->ToUserName, $keyword['reply']);
        }
    }

    private function getSystemName(){
        $system_name = M('Config')->where(array('name'=>Constants::CONFIG_SYSTEM_NAME))->getField('value');
        return $system_name;
    }

    private function bindUser($sceneId,$openId,$ToUserName){
        Log::write('openid:'.$openId,'WARN');
        Log::write('sceneId:'.$sceneId,'WARN');
        $openId = ''.$openId;
        $sceneId = ''.$sceneId;
        $logic = new UserLogic();
        $user = $logic->bindUser($openId,$sceneId);
        $system_name = $this->getSystemName();
        $item['title'] = '欢迎来到'.$system_name;
        $item['picurl'] = 'http://'.$_SERVER['HTTP_HOST'].'/Public/images/wechat_bind_bg.jpg';
        $item['url'] = $_SERVER['HTTP_HOST'];
        if($user['recommend_id'] == $sceneId){
            //新用户绑定成功
            $item['desc'] ='绑定成功！';
        }else{
            $item['desc'] = '欢迎再次使用！';
        }
        $item_list[0] = $item;
        $this->utils->msgNews($ToUserName,$openId,$item_list);
    }


    public function doSubscribe($openId,$ToUserName){

        $re = $this->utils->getNewsList();
        $item['title'] = $re->title;
        $item['desc'] = $re->digest;
        $item['picurl']  = $re->thumb_url;
        $item['url'] = $re->url;
        $item_list[0] = $item;
        $this->utils->msgNews($ToUserName,$openId,$item_list);
    }
}